package com.sctvcloud.dongqu.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.adapter.CaliNewsListAdapter;
import com.sctvcloud.dongqu.ui.util.RBaseItemDecoration;
import com.sctvcloud.dongqu.ui.utils.SkipUtil;
import com.sctvcloud.dongqu.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CaligrapherSubFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener{
    private final int WHAT_REFRESH_TIME = 919;
    @BindView(R.id.tv_living_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView calisub_list;
    private CaliNewsListAdapter calisubAdapter;
    private LinearLayoutManager manager;
    private boolean mIsLoading = false;
    private Handler handler;
    private List<NewsItem> fPrograms = new ArrayList<>();
    private List<NewsItem> list = new ArrayList<>();
    private NewsItem currentChannel;
    private CalligrapherFragment parentFragment;
    private String channelurl;
    private int newsPageAll = 1;
    private int newsIndex = 0;
    private boolean isRefresh = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg != null) {
                    handMsg(msg);
                }
            }
        };
    }

    public void setParentFragment(CalligrapherFragment parentFragment) {
        this.parentFragment = parentFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_caligraphersub, container, false);
        ButterKnife.bind(this, view);
        return view;
    }



    @Override
    public void onDestroyView() {
        if (handler != null) {
            handler.removeMessages(WHAT_REFRESH_TIME);
        }
        super.onDestroyView();
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        calisub_list.setItemAnimator(new DefaultItemAnimator());
        calisub_list.addItemDecoration(new RBaseItemDecoration(2));
        calisub_list.setLayoutManager(manager);
        if(null!= getArguments()) {
            channelurl = getArguments().getString("channelurl", "");
        }
        initData();
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
//        if (currentChannel != null && null != parentFragment) {
//            parentFragment.setPlayMedia(currentChannel, false);
//        }
        isCoverStatusColor = true;
  //      initStatusBar();

        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onLoadMore() {
        if (newsIndex < newsPageAll - 1) {
            if (!getNewsList(CalligrapherFragment.VIEWTYPE_NEWS, newsIndex + 1)) {
                Toast.makeText(getContext(), "获取更多失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
    //        if (null != calisubAdapter && calisubAdapter.getItemCount() == 0) {
                onRefresh();
    //        }
        } else {

        }
    }


    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mIsLoading = true;
//        if (TextUtils.isEmpty(((TvFragment) getParentFragment()).getProgramBackUrl())) {
//            ((TvFragment) getParentFragment()).setLoadingState(true);
//        }

        newsIndex = 0;

        isRefresh = true;
        getNewsList(CalligrapherFragment.VIEWTYPE_NEWS, 0);
    }

    private void handMsg(Message msg) {
        if (msg.what == WHAT_REFRESH_TIME) {
            handler.removeMessages(WHAT_REFRESH_TIME);
        }
    }

    public void setData(final List<NewsItem> fChannels) {
        if (null != fPrograms) {
            this.fPrograms = fChannels;
            if (calisubAdapter != null) {
                calisubAdapter.setData(fPrograms);
                calisubAdapter.notifyDataSetChanged();
            }
        }
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
    }

    /**
     * 获取 精选--视讯新闻数据
     *
     * @return
     */
    private boolean getNewsList(final int mode, final int index) {
        if (TextUtils.isEmpty(channelurl)) {
            return false;
        }

        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), channelurl, index, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem()) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                newsPageAll = getPageResponse().getData().getPageAll();
                if (ListUtils.isListValued(newsItems)) {
                    newsIndex = index;

                    if (isRefresh) {
                        list.clear();
                        list.addAll(newsItems);
                        isRefresh = false;
                    } else {
                        list.addAll(newsItems);
                    }
                    setData(list);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (newsIndex >= newsPageAll - 1) {
                    refreshLayout.setLoadMoreEnabled(false);
                } else {
                    refreshLayout.setLoadMoreEnabled(true);
                }
                onNetFinish();//暂时使用calledIndex来保存mode
            }


            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }
        });
        return true;
    }


    private void initData() {


        if (calisubAdapter == null) {
            calisubAdapter = new CaliNewsListAdapter(getContext(), fPrograms, 0).setItemInternalClick(livingOnItemClick);
            calisub_list.setAdapter(calisubAdapter);
        } else {
            calisubAdapter.addDatas(fPrograms);
            calisubAdapter.notifyDataSetChanged();
        }
        onRefresh();
    }

    int oldPos = -1;
    private OnItemInternalClick livingOnItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            NewsItem fProgram = calisubAdapter.getItem(position);
            if (null != fProgram) {
   //             currentChannel = fProgram;
   //             if (null != parentFragment) {
   //                 parentFragment.setPlayMedia(fProgram, false);
   //             }

   //             initStatusBar();

                calisubAdapter.setSelectPos(position);
                calisubAdapter.notifyDataSetChanged();
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("页面", "首页"));
                pairs.add(new Pair<>("栏目", tag));
                pairs.add(new Pair<>("行为类型", "点击"));
                GridsumWebDissector.getInstance().trackEvent(CaligrapherSubFragment.this, "", ((NewsItem) calisubAdapter.getItem(position)).getNewsTitle(), "", 200, pairs);

                HashMap<String, String> map = new HashMap<>();
                for (Pair<String, String> p : pairs) {
                    map.put(p.first, p.second);
                }
                SkipUtil.skipWithNewsItem(getActivity(), (NewsItem) calisubAdapter.getItem(position), map);
            }
        }
    };

    public void setChannelurl(String channelurl) {
        this.channelurl = channelurl;
    }

    public String getChannelurl() {
        return this.channelurl;
    }
}
